package com.edu.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.edu.common.exception.ServiceException;
import com.edu.common.utils.file.ImageUtils;
import com.edu.system.domain.Student;
import com.edu.system.domain.TClass;
import com.edu.system.domain.TClassExt;
import com.edu.system.domain.TClassroom;
import com.edu.system.mapper.TClassExtMapper;
import com.edu.system.mapper.TClassMapper;
import com.edu.system.mapper.TClassroomMapper;
import com.edu.system.service.IStudentService;
import com.edu.system.service.ITClassService;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 班级Service业务层处理
 *
 * @author xxxx
 * @date 2023-12-28
 */
@Slf4j
@Service
public class TClassServiceImpl implements ITClassService {
    @Autowired
    private TClassMapper tClassMapper;
    @Resource
    private TClassroomMapper tClassroomMapper;
    @Resource
    private TClassExtMapper tClassExtMapper;
    
    @Resource
    private IStudentService studentService;

    @Value("${avatar.classDefault}")
    private String classDefaultImage;

    /**
     * 查询班级
     *
     * @param id 班级主键
     * @return 班级
     */
    @Override
    public TClass selectTClassById(Long id) {
        TClass oclass = tClassMapper.selectTClassById(id);
        if(null != oclass) {
        	Student query = new Student();
        	query.setClassId(id);
        	int num = studentService.countStudentNum(query);
        	oclass.setStudentNum(num);
        }
        return oclass;
    }

    @Override
    public TClass selectTClassByRoomId(Long roomId) {
        TClass c = new TClass();
        c.setRoomId(roomId);
        return Optional.ofNullable(this.selectTClassList(c))
            .filter(a -> a.size() > 0)
            .map(a -> a.get(0))
            .orElseGet(() -> null);
    }

    /**
     * 查询班级列表
     *
     * @param tClass 班级
     * @return 班级
     */
    @Override
    public List<TClass> selectTClassList(TClass tClass) {
        List<TClass> tClasses = tClassMapper.selectTClassList(tClass);
        for (TClass c : tClasses){
            c.setName(joinClassName(c));
        }
        return tClasses;
    }

    public String joinClassName(TClass c) {
        return c.getCohort().contains("届") ? c.getCohort() : c.getCohort() + "届" + c.getName();
    }

    @Override
    public List<TClass> selectRealList(TClass tClass) {
        return tClassMapper.selectRealList(tClass);
    }


    @Override
    public List<TClass> selectTClassList(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return new ArrayList<>();
        }
        return tClassMapper.listByIds(ids)
            .stream()
            .peek(c -> c.setName(joinClassName(c)))
            .collect(Collectors.toList());
    }

    @Override
    public Map<Long, TClass> selectTClassMap(List<Long> ids) {
        return this.selectTClassList(ids)
            .stream()
            .collect(Collectors.toMap(TClass::getId, b->b));
    }

    @Override
    public Map<Long, String> selectIdNameMap(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return new HashMap<>();
        }
        return this.selectTClassList(ids)
            .stream()
            .collect(Collectors.toMap(TClass::getId, TClass::getName));
    }

    @Override
    public Map<String, Long> selectNameMap(List<String> classNames) {
        return tClassMapper.listByNames(classNames)
            .stream().collect(Collectors.toMap(TClass::getName, TClass::getId));
    }

    @Override
    public String queryTClassNames(String ids) {
        if (StrUtil.isBlank(ids)){
            return Strings.EMPTY;
        }
        return this.selectTClassList(
            Stream.of(ids.split(",")).map(Long::parseLong).collect(Collectors.toList())
        ).stream().map(TClass::getName).collect(Collectors.joining(","));
    }

    @Override
    public List<TClassExt> findClassExtByClassId(Long roomId) {
        TClassroom classroom = tClassroomMapper.selectTClassroomById(roomId);
        if (classroom == null){
            log.error("对应的教室未找到,教室id:{}", roomId);
            return new ArrayList<>();
        }
        return tClassExtMapper.selectByLocationId(classroom.getCode());
    }


    /**
     * 新增班级
     *
     * @param tClass 班级
     * @return 结果
     */
    @Override
    public int insertTClass(TClass tClass) {
        if (StrUtil.isBlank(tClass.getImage())){
            tClass.setImage(ImageUtils.getDefaultImage(classDefaultImage));
        }
        if (tClass.getRoomId() != null){
            TClassroom classroom = tClassroomMapper.selectTClassroomById(tClass.getRoomId());
            tClass.setRoomName(classroom.getName());
        }
        validClassIsExist(tClass.getName(), tClass.getCohort(), null);
        return tClassMapper.insertTClass(tClass);
    }

    private void validClassIsExist(String className, String cohort, Long id) {
        TClass c = new TClass();
        c.setName(className);
        c.setCohort(cohort);
        List<TClass> tClasses = tClassMapper.selectTClassList(c)
            .stream()
            .filter(a -> !a.getId().equals(id))
            .collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(tClasses)){
            throw new ServiceException("该届的班级已存在");
        }
    }

    /**
     * 修改班级
     *
     * @param tClass 班级
     * @return 结果
     */
    @Override
    public int updateTClass(TClass tClass) {
        if (tClass.getRoomId() != null){
            TClassroom classroom = tClassroomMapper.selectTClassroomById(tClass.getRoomId());
            tClass.setRoomName(classroom.getName());
        }
        validClassIsExist(tClass.getName(), tClass.getCohort(), tClass.getId());
        return tClassMapper.updateTClass(tClass);
    }

    /**
     * 批量删除班级
     *
     * @param ids 需要删除的班级主键
     * @return 结果
     */
    @Override
    public int deleteTClassByIds(Long[] ids) {

        return tClassMapper.deleteTClassByIds(ids);
    }

    /**
     * 删除班级信息
     *
     * @param id 班级主键
     * @return 结果
     */
    @Override
    public int deleteTClassById(Long id) {
        return tClassMapper.deleteTClassById(id);
    }
    
    @Override
    public List<TClass> getHonorsClassByClassId(long classId) {
    	TClass oClass = this.selectTClassById(classId);
    	if(null != oClass) {
    		return this.getHonorsClassByCohort(oClass.getCohort());
    	}
    	return new ArrayList<TClass>();
    }
    @Override
    public List<TClass> getHonorsClassByCohort(String cohort) {
    	TClass query = new TClass();
    	query.setCohort(cohort);
    	List<TClass> tClasses = tClassMapper.selectHonorsClassList(query);
    	for (TClass c : tClasses){
            c.setName(joinClassName(c));
        }
    	return tClasses;
    }
}
